<template>
  <view class="container">
    <!-- Logo & 标题 -->
    <view class="logo-section">
      <image src="/static/img/logo.png" class="logo-img"></image>
              <text class="app-title">Pawtrack 登录</text>
    </view>

    <!-- 登录方式切换 -->
    <view class="login-tabs">
      <view 
        class="login-tab" 
        :class="{active: loginType === 'account'}" 
        @click="loginType = 'account'"
      >账号登录</view>
      <view 
        class="login-tab" 
        :class="{active: loginType === 'phone'}" 
        @click="loginType = 'phone'"
      >手机登录</view>
    </view>

    <!-- 登录表单 -->
    <view class="form-container">
             <!-- 账号密码登录表单 -->
       <view v-if="loginType === 'account'" class="login-form">
         <input v-model="account.username" placeholder="请输入账号" class="input" />
         <input v-model="account.password" placeholder="请输入密码" class="input" type="password" />
         <!-- 验证码 -->
         <view class="captcha-row" v-if="captchaEnabled">
           <input v-model="account.code" placeholder="请输入验证码" class="input captcha-input" maxlength="4" />
           <view class="captcha-img" @click="refreshCaptcha">
             <image :src="captchaUrl" class="captcha-image" mode="aspectFit" />
           </view>
         </view>
         <button class="login-btn" @click="handleLogin" :disabled="loading">
           {{ loading ? '登录中...' : '登录' }}
         </button>
       </view>

      <!-- 手机号验证码登录表单 -->
      <view v-if="loginType === 'phone'" class="login-form">
        <input v-model="phone.phone" placeholder="请输入手机号" class="input" maxlength="11" />
        <view class="code-row">
          <input v-model="phone.code" placeholder="请输入验证码" class="input code-input" maxlength="6" />
          <button class="code-btn" :disabled="codeTimer > 0 || loading" @click="sendCode">
            {{ codeTimer > 0 ? codeTimer + 's' : '获取验证码' }}
          </button>
        </view>
        <button class="login-btn" @click="handlePhoneLogin" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </view>
    </view>



    <!-- 底部提示 -->
    <view class="bottom-hint">
      <text>还没有账号？</text>
      <button class="switch-btn" @click="goToRegister">立即注册</button>
    </view>
  </view>
</template>

<script>
import { loginByAccount, loginByPhone, loginByWeChat, sendSmsCode, getCodeImg } from '@/api/login.js';
import { setToken, getToken } from '@/utils/request.js';
import userStore from '@/store/user.js';
import { API_BASE } from '@/config/config.js';

// 调试：检查userStore是否正确导入
// console.log('[Login] userStore:', userStore);
// console.log('[Login] userStore.dispatch:', userStore?.dispatch);
// console.log('[Login] userStore type:', typeof userStore);

export default {
  data() {
    return {
      loginType: 'account',
      account: {
        username: '',
        password: '',
        code: '',
        uuid: ''
      },
      phone: {
        phone: '',
        code: ''
      },

      codeTimer: 0,
      codeInterval: null,
      loading: false,
      // 验证码相关
      captchaEnabled: true,
      captchaUrl: '',
      captchaUuid: ''
    };
  },
  
  created() {
    // 组件初始化时获取验证码
    this.getCaptcha();
  },
  methods: {
     // 获取验证码
     async getCaptcha() {
       try {
         const captchaUrl = `${API_BASE}/captchaImage`;
         
         const response = await new Promise((resolve, reject) => {
           uni.request({
             url: captchaUrl,
             method: 'GET',
             header: {
               'isToken': false,
               'Content-Type': 'application/json'
             },
             success: (res) => {
               resolve(res);
             },
             fail: (err) => {
               reject(err);
             }
           });
         });

         let data = null;
         if (response && response.data) {
           data = response.data;
         } else if (response && typeof response === 'object' && response.code !== undefined) {
           data = response;
         } else if (Array.isArray(response) && response.length > 0) {
           data = response[0];
         } else {
           throw new Error('无法获取响应数据');
         }

         if (!data || typeof data !== 'object') {
           throw new Error('验证码响应格式无效');
         }

         if (data.code === 401) {
           throw new Error(data.msg || '认证失败');
         }
         this.captchaEnabled = data.captchaEnabled === undefined ? true : !!data.captchaEnabled;
         if (this.captchaEnabled) {
           if (data.img && data.uuid) {
             this.captchaUrl = 'data:image/gif;base64,' + data.img;
             this.captchaUuid = data.uuid;
             this.account.uuid = data.uuid;
           } else {
             throw new Error('验证码数据不完整');
           }
         }
       } catch (error) {
         const errorMessage = error?.message || error?.errMsg || '未知错误';
         this.captchaEnabled = false;
         uni.showToast({ title: '获取验证码失败: ' + errorMessage, icon: 'none', duration: 3000 });
       }
     },
     
     // 刷新验证码
     refreshCaptcha() {
       this.getCaptcha();
     },
     
          // 账号密码登录
      async handleLogin() {
       if (!this.account.username || !this.account.password) {
         uni.showToast({ title: '请输入账号和密码', icon: 'none' });
         return;
       }
       
       // 检查验证码
       if (this.captchaEnabled && (!this.account.code || !this.account.code.trim())) {
         uni.showToast({ title: '请输入验证码', icon: 'none' });
         return;
       }
      this.loading = true;
      try {
         // 准备登录数据
         const loginData = {
           username: this.account.username,
           password: this.account.password
         };
         
         // 如果启用了验证码，添加验证码参数
         if (this.captchaEnabled) {
           loginData.code = this.account.code;
           loginData.uuid = this.captchaUuid;
         }
         
           // 账号密码登录
           const res = await new Promise((resolve, reject) => {
             uni.request({
               url: `${API_BASE}/login`,
               method: 'POST',
               data: loginData,
               header: {
                 'isToken': false,
                 'Content-Type': 'application/json'
               },
               success: (res) => {
                 resolve(res.data);
               },
               fail: (err) => {
                 reject(err);
               }
             });
           });
          if (res.code === 200) {
            const { token, user } = res
            
            uni.setStorageSync('token', token);

            if (user) {
              const userInfo = {
                userId: user.userId || user.id,
                nickName: user.nickName || user.userName,
                userName: user.userName,
                avatar: user.avatar,
                email: user.email,
                phonenumber: user.phonenumber,
                sex: user.sex
              };
              uni.setStorageSync('userInfo', userInfo);
              if (userInfo.userId) {
                uni.setStorageSync('userId', userInfo.userId);
                }
            } else {
              try {
                const userInfoRes = await new Promise((resolve, reject) => {
                  uni.request({
                    url: `${API_BASE}/getInfo`,
                    method: 'GET',
                    header: {
                      'Authorization': 'Bearer ' + token,
                      'Content-Type': 'application/json'
                    },
                    success: (res) => {
                      resolve(res.data);
                    },
                    fail: (err) => {
                      reject(err);
                    }
                  });
                });
                
                if (userInfoRes && userInfoRes.code === 200) {
                  const userData = userInfoRes.user || userInfoRes.data;
                  if (userData) {
                    const userInfo = {
                      userId: userData.userId || userData.id,
                      nickName: userData.nickName || userData.userName,
                      userName: userData.userName,
                      avatar: userData.avatar,
                      email: userData.email,
                      phonenumber: userData.phonenumber,
                      sex: userData.sex
                    };
                    uni.setStorageSync('userInfo', userInfo);
                    if (userInfo.userId) {
                      uni.setStorageSync('userId', userInfo.userId);
                    }
                  }
                }
              } catch (error) {
                uni.showToast({ title: '获取用户信息失败', icon: 'none' });
            }
            }
            
            // 验证本地存储
            const savedToken = uni.getStorageSync('token')
            const savedUserInfo = uni.getStorageSync('userInfo')
            const savedUserId = uni.getStorageSync('userId')
            // console.log('[Login] 验证本地存储 - token:', savedToken)
            // console.log('[Login] 验证本地存储 - userInfo:', savedUserInfo)
            // console.log('[Login] 验证本地存储 - userId:', savedUserId)
            
            // 尝试使用userStore，如果失败则使用本地存储
            try {
              // 存储 token 和用户信息
              userStore.dispatch('user/setToken', token)
              
              // 然后获取完整的用户信息
              userStore.dispatch('user/fetchUserInfo').then(() => {
                // console.log('User info fetched successfully')
              }).catch(error => {
                // console.error('Failed to fetch user info:', error)
              })
            } catch (storeError) {
              // console.error('userStore error, using local storage:', storeError)
              // 如果userStore失败，只使用本地存储
            }
            
            uni.showToast({ title: '登录成功', icon: 'success' })
            
            // 延迟跳转，让用户看到成功提示
            setTimeout(() => {
              uni.reLaunch({ url: '/pages/index/index' })
            }, 1500)
          } else {
            uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
            if (this.captchaEnabled) this.refreshCaptcha();
          }
       } catch (error) {
         uni.showToast({ title: error.message || '登录失败', icon: 'none' });
         // 登录失败时刷新验证码
         if (this.captchaEnabled) {
           this.refreshCaptcha();
         }
       } finally {
         this.loading = false;
       }
    },

    // 手机验证码登录
    async handlePhoneLogin() {
      if (!/^1[3-9]\d{9}$/.test(this.phone.phone)) {
        uni.showToast({ title: '请输入正确手机号', icon: 'none' });
        return;
      }
      if (!/^\d{4,6}$/.test(this.phone.code)) {
        uni.showToast({ title: '请输入验证码', icon: 'none' });
        return;
      }
      
      this.loading = true;
      try {
        const res = await loginByPhone(this.phone);
        if (res.code === 200) {
          const token = res.token || (res.data && res.data.token);
          if (token) {
            setToken(token);
            await this.fetchAndStoreUserInfo();
            uni.showToast({ title: '登录成功', icon: 'success' });
                // 直接跳转到首页
                uni.reLaunch({ url: '/pages/index/index' });
          } else {
            uni.showToast({ title: '登录成功但token获取失败', icon: 'none' });
          }
        } else {
          uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: error.message || '登录失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 发送验证码
    async sendCode() {
      if (!/^1[3-9]\d{9}$/.test(this.phone.phone)) {
        uni.showToast({ title: '请输入正确手机号', icon: 'none' });
        return;
      }
      
      try {
        const res = await sendSmsCode(this.phone.phone);
        
        if (res.code === 200) {
          uni.showToast({ title: '验证码已发送', icon: 'success' });
          this.startCodeTimer();
        } else {
          uni.showToast({ title: res.msg || '发送失败', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: error.message || '发送失败', icon: 'none' });
      }
    },

    // 开始验证码倒计时
    startCodeTimer() {
      this.codeTimer = 60;
      this.codeInterval = setInterval(() => {
        this.codeTimer--;
        if (this.codeTimer <= 0) {
          clearInterval(this.codeInterval);
        }
      }, 1000);
    },



    // 获取并存储用户信息（与 ruoyi-ui 一致）
    async fetchAndStoreUserInfo() {
        try {
          const res = await new Promise((resolve, reject) => {
            uni.request({
              url: `${API_BASE}/getInfo`,
              method: 'GET',
              header: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
              },
              success: (res) => {
                resolve(res.data);
              },
              fail: (err) => {
                reject(err);
              }
            });
          });
          
          if (res.code === 200) {
            const userData = res.user || res.data;
            if (!userData) throw new Error('未能获取有效的用户数据');
            
            // 使用新的 store 方法
            userStore.dispatch('user/fetchUserInfo').then(() => {
              // console.log('User info fetched and stored successfully')
            }).catch(error => {
              // console.error('Failed to store user info:', error)
            })
          } else {
            throw new Error(res.msg || '获取用户信息失败');
          }
        } catch (error) {
          uni.showToast({ title: '获取用户信息失败: ' + (error.message || '未知错误'), icon: 'none' });
        }
      },


    // 微信登录
    loginByWeChat() {
      // #ifdef MP-WEIXIN
      uni.login({
        provider: 'weixin',
        success: async (loginRes) => {
          const code = loginRes.code;
          try {
            const res = await new Promise((resolve, reject) => {
              uni.request({
                url: `${API_BASE}/login/wechat`,
                method: 'POST',
                data: { code },
                header: {
                  'isToken': false,
                  'Content-Type': 'application/json'
                },
                success: (res) => {
                  resolve(res.data);
                },
                fail: (err) => {
                  reject(err);
                }
              });
            });
            
            if (res.code === 200) {
              const token = res.token || (res.data && res.data.token);
              if (token) {
                // 保存token到本地存储
                uni.setStorageSync('token', token)
                
                // 尝试使用userStore，如果失败则使用本地存储
                try {
                  // 使用新的 store 方法
                  userStore.dispatch('user/setToken', token)
                  userStore.dispatch('user/fetchUserInfo').then(() => {
                    // console.log('User info fetched successfully')
                  }).catch(error => {
                    // console.error('Failed to fetch user info:', error)
                  })
                } catch (storeError) {
                  // console.error('userStore error, using local storage:', storeError)
                  // 如果userStore失败，只使用本地存储
                }
                
                uni.showToast({ title: '登录成功', icon: 'success' });
                
                // 跳转到首页
                uni.reLaunch({ url: '/pages/index/index' });
              }
            } else {
              uni.showToast({ title: res.msg || '微信登录失败', icon: 'none' });
            }
          } catch (error) {
            uni.showToast({ title: error.message || '微信登录失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.showToast({ title: '微信授权失败', icon: 'none' });
        }
      });
      // #endif
      // #ifndef MP-WEIXIN
      uni.showToast({ title: '请在微信小程序中使用', icon: 'none' });
      // #endif
    },
    goToRegister() {
      uni.navigateTo({ url: '/pages/register' });
    }
  },
  
  onLoad() {
    // 页面加载时获取验证码
    this.getCaptcha();
  },
  
  onUnload() {
    if (this.codeInterval) {
      clearInterval(this.codeInterval);
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 40rpx 20rpx 0 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}
.logo-img {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}
.app-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #007AFF;
}
.mode-switch {
  display: flex;
  width: 100%;
  margin-bottom: 30rpx;
  background: #fff;
  border-radius: 15rpx;
  padding: 10rpx;
}
.mode-tab {
  flex: 1;
  text-align: center;
  font-size: 30rpx;
  padding: 20rpx 0;
  color: #999;
  border-radius: 10rpx;
  font-weight: bold;
}
.mode-tab.active {
  color: #007AFF;
  background: #f0f8ff;
}
.login-tabs {
  display: flex;
  width: 100%;
  margin-bottom: 30rpx;
}
.login-tab {
  flex: 1;
  text-align: center;
  font-size: 30rpx;
  padding: 20rpx 0;
  color: #999;
  border-bottom: 4rpx solid transparent;
  font-weight: bold;
}
.login-tab.active {
  color: #007AFF;
  border-bottom: 4rpx solid #007AFF;
}
.form-container {
  width: 100%;
}
.login-form {
  width: 100%;
  background: #fff;
  border-radius: 15rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.06);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.input, .picker {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-bottom: 30rpx;
  background: #f8f8f8;
}
.picker-text {
  color: #333;
}
.code-row {
  display: flex;
  width: 100%;
  margin-bottom: 30rpx;
}
.code-input {
  flex: 2;
  margin-right: 20rpx;
}
.code-btn {
  flex: 1;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
  padding: 20rpx 0;
}

/* 验证码样式 */
.captcha-row {
  display: flex;
  width: 100%;
  margin-bottom: 30rpx;
}

.captcha-input {
  flex: 2;
  margin-right: 20rpx;
}

.captcha-img {
  flex: 1;
  height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  overflow: hidden;
  cursor: pointer;
}

.captcha-image {
  width: 100%;
  height: 100%;
}
.login-btn {
  width: 100%;
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 30rpx;
  padding: 20rpx 0;
  margin-top: 10rpx;
}
.bottom-hint {
  margin-top: 40rpx;
  display: flex;
  align-items: center;
}
.switch-btn {
  background: none;
  color: #007AFF;
  border: none;
  font-size: 28rpx;
  margin-left: 10rpx;
  text-decoration: underline;
}
</style>